package kn.webstd.g4g;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import kn.webstd.bc.user.business.IUserRegistrationService;
import kn.webstd.g4g.business.UserSampleUserAdapterService;
import kn.webstd.tools.business.ApplicationContext;
import kn.webstd.tools.business.BusinessComponentContainer;
import kn.webstd.tools.business.security.impl.AuthorizationManager;

import org.apache.log4j.Logger;

/**
 * EXAMPLE: This class is used to initialize the Business Component framework on the server side. Use it as a template for your
 * own project and add other initializations needed by your application at startup time.
 * 
 * {@link ServletContextListener} that is executed once during application startup. It is responsible for initializing the
 * application. For the sample application the following steps are performed:
 * <ul>
 * <li>overrides the default locale on the machine the application is running on to the one defined in properties-files</li>
 * <li>the {@link BusinessComponentContainer} is initialized. This starts the connection pools and instantiates all services</li>
 * <li>set the {@link BusinessComponentContainer} as the service factory for the WebStd {@link ApplicationContext}</li>
 * <li>
 * </ul>
 * <p>
 * 
 * @author Fabian Linz
 */
public class ApplicationStartupListener implements ServletContextListener {

    private static final transient Logger logger = Logger.getLogger(ApplicationStartupListener.class);

    /**
     * {@inheritDoc}
     */
    public void contextInitialized(ServletContextEvent event) {
        try {
            // No user session here, so disable authorization during initialization
            AuthorizationManager.setAuthorized(Boolean.TRUE);

            BusinessComponentContainer container = BusinessComponentContainer.getInstance();
            logger.info("business component container initialized");

            // set the business component container as service factory for the GWT ServerEnvironment
            ApplicationContext.setServiceFactory(container);
            logger.info("service factory set in the ApplicationContext");
            
            // IMPORTANT! for the user session.
            container.createService(IUserRegistrationService.class).register(new UserSampleUserAdapterService());
        } finally {
            AuthorizationManager.setAuthorized(Boolean.FALSE);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void contextDestroyed(ServletContextEvent event) {
        // nothing to do
    }
}